iT邦幫忙

2021 iThome 鐵人賽

DAY 21
0
Software Development

iOS 學習筆記系列 第 22

Day22 URLSession 02 - GET

  • 分享至 

  • xImage
  •  

GET:取資料

同樣根據以上的Reqres API 來示範

首先一樣根據Response 建立Model

User.swift :

struct UserGetResponse: Decodable {
    let page : Int
    let perPage : Int
    let total: Int
    let totalPages : Int
    let data : [User]
}

struct User : Decodable, Hashable {
    let id : Int
    let email : String
    let firstName : String
    let lastName : String
    let avatar : String
}

接著在UserURLSession.swift處理關於URLSession的事件

    func userGetRequest(page: Int, completionHandler: @escaping (UserGetResponse) -> Void) {
        
        let url = URL(string: "https://reqres.in/api/users?page=\(page)")!
        
        let request = URLRequest(url: url)
        
        URLSession.shared.dataTask(with: request) {
            data, response, error in
            if let data = data {
                do {
                    let decoder = JSONDecoder()
                    decoder.keyDecodingStrategy = .convertFromSnakeCase
                    
                    let response = try decoder.decode(UserGetResponse.self, from: data)
                    
                    completionHandler(response)
                    
                }catch(let error) {
                    print(error.localizedDescription)
                }
            } else {
                print("No Data")
            }
        }.resume()
    }

之後在View 設計畫面並使用
GETSampleView.swift

import SwiftUI

struct GETSampleView: View {
    @State private var users: [User] = []

    var body: some View {
        NavigationView {
            VStack {
                Button {
                    UserURLSession.shared.userGetRequest(page: 1) { response in
                        DispatchQueue.main.async {
                            users = response.data
                        }
                    }

                } label: {
                    Text("GET Request")
                }
                ScrollView {
                    LazyVStack {
                        ForEach(users, id: \.self) { user in
                            UserItemView(user: user)
                        }
                    }
                }
                .cornerRadius(8)
                
            }            
            .navigationBarTitleDisplayMode(.inline)
            .navigationTitle(Text("URLSession GET Sample"))
        }
    }
}

struct GETSampleView_Previews: PreviewProvider {
    static var previews: some View {
        GETSampleView()
    }
}

這邊所有URLSession 的範例一起放在Github: URLSessionSample 供大家參考


上一篇
Day21 URLSession 01 - POST
下一篇
Day23 URLSession 03 - PUT / PATCH
系列文
iOS 學習筆記30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言